import { useEffect, useState } from 'react';
import { Form, Input, Button, Checkbox, Select, InputNumber, Flex, message } from 'antd';
import CaptchaFormItem from '@/components/CaptchaFormItem'
import { useNavigate } from 'react-router-dom';
import { v4 as uuidv4 } from 'uuid';
import { captcha, emailCode, forgetPassword } from '@/service';
import { useTranslation } from 'react-i18next';

import styles from './index.module.scss';

export default () => {
    const [uuid, setUuid] = useState('');
    const [captchaUrl, setCaptchaUrl] = useState('');
    const [messageApi, contextHolder] = message.useMessage();
    const [countdown, setCountdown] = useState(0);
    const [isLoading, setIsLoading] = useState(false);
    const { t } = useTranslation();
    const initState = () => ({
    }),
        navigate = useNavigate(),
        [state, setState] = useState(initState);
    const [form] = Form.useForm(); // 创建表单实例
    const onSubmit = async () => {
        try {
            const values = await form.validateFields();
            if (values.email) {
                values.email = values.email.replace(/\s+/g, '');
            }
            const res = await forgetPassword({ email: values.email, code: values.code, password: values.password, repassword: values.repassword });
            const { code, message } = res || {};
            if (code === 0) {
                messageApi.open({
                    type: 'success',
                    content: message
                });
                navigate('/login');
            } else {
                messageApi.open({
                    type: 'error',
                    content: message
                });
            }
        } catch (error) {
            if (error?.message) {
                messageApi.open({
                    type: 'error',
                    content: error?.message
                });
            }
        }
    }
    const validateEmail = (rule, value) => {
        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!value) {
            return Promise.reject(new Error(t('common.modal.Emailplacehoder')));
        }
        else if (!emailRegex.test(value.trim())) {
            return Promise.reject(new Error(t('common.modal.correctEmailplacehoder')));
        }
        return Promise.resolve();
    };
    const validateCaptCha = (rule, value) => {
        if (!value) {
            return Promise.reject(new Error(t('common.modal.verificationCodeplacehoder')));
        }
        return Promise.resolve();
    };
    const handleVerify = () => {
        const newUuid = uuidv4().replace(/-/g, '').substring(0, 32);
        setUuid(newUuid);
        fetchCaptcha(newUuid);
    };
    const fetchCaptcha = async (uuid) => {
        try {
            let params = { uuid };
            const response = await captcha(params);
            const imageUrl = URL.createObjectURL(response);
            setCaptchaUrl(imageUrl);
        } catch (error) {
            console.error('Error fetching captcha:', error);
        }
    };
    const getEmailCode = async () => {
        if (countdown > 0) return;
        try {
            setIsLoading(true);

            let params = {
                uuid: uuid,
                email: form.getFieldValue('email') ? form.getFieldValue('email').trim() : '',
                captcha: form.getFieldValue('captcha') || ''
            };
            const response = await emailCode(params);
            const { code, message } = response || {};
            if (code === 0) {
                messageApi.open({
                    type: 'success',
                    content: message
                });
                setCountdown(60);
            } else {
                messageApi.open({
                    type: 'error',
                    content: message
                });
            }
        } catch (error) {
            if (error?.message) {
                messageApi.open({
                    type: 'error',
                    content: error?.message,
                });
            }
        } finally {
            setIsLoading(false);
        }
    };
    // 启动倒计时逻辑
    useEffect(() => {
        let timer;
        if (countdown > 0) {
            timer = setTimeout(() => {
                setCountdown(countdown - 1);
            }, 1000);
        }
        return () => clearTimeout(timer);
    }, [countdown]);
    useEffect(() => {
        const initialUuid = uuidv4().replace(/-/g, '').substring(0, 32);
        setUuid(initialUuid);
        fetchCaptcha(initialUuid);
    }, []);
    const tailFormItemLayout = {
        wrapperCol: {
            xs: {
                span: 24,
                offset: 0,
            },
            sm: {
                span: 13,
                offset: 7,
            },
        },
    };
    return (
        <div className={styles['container']}>
            <div className={styles.signBox}>
                <div className={styles.title}>{t('common.forgetPsd.title')}</div>
                <Form
                    name="forgetPsd"
                    className='custom-form-primary'
                    labelCol={{ span: 7 }}
                    wrapperCol={{ span: 13 }}
                    form={form}
                >
                    <Form.Item
                        label={t('common.modal.label.email')}
                        name="email"
                        rules={[
                            {
                                required: true,
                                validator: validateEmail,
                            },
                        ]}
                    >
                        <Input type="text" placeholder={t('common.modal.enterPlacehoder')} />
                    </Form.Item>

                    <Form.Item
                        label={t('common.modal.label.verificationCode')}
                        name="captcha"
                        rules={[
                            {
                                required: true,
                                validator: validateCaptCha,
                            },
                        ]}
                    >
                        <CaptchaFormItem onVerify={handleVerify} captchaUrl={captchaUrl} />
                    </Form.Item>
                    <Form.Item
                        label={t('common.modal.label.emailCode')}
                        name="code"
                        rules={[
                            {
                                required: true,
                                message: t('common.modal.emailverificationCodeplacehoder'),
                            },
                        ]}
                    >
                        <Input
                            placeholder={t('common.modal.enterPlacehoder')}
                            addonAfter={
                                <Button
                                    type="link"
                                    onClick={getEmailCode}
                                    disabled={countdown > 0 || isLoading}
                                >
                                    {countdown > 0 ? t('common.signUp.countDown', { countdown }) : t('common.modal.getEmailCodeBtn')}
                                </Button>
                            }
                        />
                    </Form.Item>
                    <Form.Item
                        label={t('common.modal.label.passwardNew')}
                        name="password"
                        rules={[{ required: true, message: t('common.modal.newPasswordplacehoder') }]}
                    >
                        <Input type="text" placeholder={t('common.modal.enterPlacehoder')} />
                    </Form.Item>
                    <Form.Item
                        label={t('common.modal.label.reEnter')}
                        name="repassword"
                        rules={[
                            { required: true, message: t('common.modal.newPasswordReplacehoder') },
                            ({ getFieldValue }) => ({
                                validator(_, value) {
                                    if (!value || getFieldValue('password') === value) {
                                        return Promise.resolve();
                                    }
                                    return Promise.reject(new Error(t('common.modal.passwordinconsistencyPlacehoder')));
                                },
                            }),
                        ]}
                    >
                        <Input type="text" placeholder={t('common.modal.enterPlacehoder')} />
                    </Form.Item>
                    <div className={styles.btnGroup}>
                        <Form.Item {...tailFormItemLayout}>
                            <Button type='primary' htmlType="submit" onClick={onSubmit}>
                                {t('common.modal.button.SubmitBtn')}
                            </Button>
                        </Form.Item>
                    </div>
                </Form>
            </div>
            {contextHolder}
        </div>
    );
}